package com.tpl.core.basedata.action.sys;

import java.util.List;

import com.tpl.core.JsonUtil;
import com.tpl.core.action.BaseAction;
import com.tpl.core.action.SessionUtil;
import com.tpl.core.basedata.common.constant.ICacheConstants;
import com.tpl.core.service.DataDictService;
import com.tpl.core.basedata.service.DeptService;
import com.tpl.core.basedata.service.DeptUserService;
import com.tpl.core.basedata.service.sys.FileService;
import com.tpl.core.common.DateUtil;
import com.tpl.core.common.TreeHelper;
import com.tpl.core.common.ValidateUtil;
import com.tpl.core.common.exception.RuleException;
import com.tpl.core.common.page.Page;
import com.tpl.core.common.redis.RedisClientUtil;
import com.tpl.core.entity.SessionUser;
import com.tpl.core.entity.sys.Dept;
import com.tpl.core.entity.sys.User;
import com.alibaba.fastjson.JSONArray;
import com.tpl.core.service.ExecuteSqlService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * 说明 :部门管理视图层
 * 
 * @author <a href="mailto:3380084@gmail.com">张坤雷</a>
 * @version 创建时间：2013-7-2 下午5:25:04
 *
 */
@Controller
@RequestMapping("/deptUser")
public class DeptUserAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5933687736866611846L;
	@Autowired
	private DeptUserService deptUserService;
	@Autowired
	private DeptService deptService;

	@RequestMapping("/edit.do")
	public String toEdit(Long id, Long deptId) {
		if (id != null) {
			User user = deptUserService.getUserById(id);
			// user.setExpand(expandService.getExpand(ExpandEnum.USER,
			// user.getId()));
			putInRequest("users", user);
		}
		putInRequest("deptId", deptId);
		return "system/deptUser_userEdit";
	}

	@RequestMapping("/toDeptUserManage.do")
	public String toDeptUserManage() {
		return "dept/deptUserManage";
	}

	@RequestMapping("/toDeptUserList.do")
	public String toDeptUserList() {
		putInRequest("tf", 0);
		return "dept/deptUser_list";
	}

	@RequestMapping("/getDeptUserList.do")
	public String getDeptUserList(Long deptId, User user,Long tf) {
		if(tf==null){
			tf=0l;
		}
		Page page = null;
		Dept dept = new Dept();
		if (deptId != null && deptId > 0) {
			page = deptUserService.getUsersByDeptId2(deptId, user, getPageIndex(), getPageSize(),tf);
			dept = deptService.getDeptById(deptId);
		}
		long loginDeptId= SessionUtil.getLoginDeptId();
		putInRequest("dept", dept);

		putInRequest("page", page, "deptId", deptId, "user", user,"loginDeptId",loginDeptId,"tf",tf);

		return "dept/user_list";
	}

	@RequestMapping("/save.do")
	public @ResponseBody void doSaveOrUpdate(User user, Long deptId) {


		ValidateUtil.validLength(user.getUserName(), 2, 20, "人员姓名");
//		if (StringUtils.isNotEmpty(user.getIdCard())) {
//			ValidateUtil.validIdCard(user.getIdCard(), "身份证号");
//			user.setUserNo(user.getIdCard());
//		}
		user.setUserNo(user.getIdCard());
		ValidateUtil.validISO88591(user.getUserNo(), "登录名称", true);
		//ValidateUtil.validPhone(user.getTelPhone(), "联系电话", true);对验证手机和电话的bug的修改
		String th="((\\d{11})|^((\\d{7,8})|(\\d{4}|\\d{3})-(\\d{7,8})|(\\d{4}|\\d{3})-(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1})|(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1}))$)";
		if(StringUtils.isNotBlank(user.getTelPhone())&&!user.getTelPhone().matches(th)){
			throw new RuleException("请输入手机号11位或电话号（允许分区和分机）");}
		ValidateUtil.validPhone(user.getMobilePhone(), "手机号码", true);
//		ValidateUtil.validEmail(user.getEmail(), "邮箱地址", true);
		user.setUpdateDate(DateUtil.now());
		user.setUpdator(getLoginUser().getUserNo());
		deptUserService.doSave(user, deptId);
		// Render.update(RenderKey.USER,user);
		outJsonSuccess();
	}

	@RequestMapping("/getUserDepts.do")
	public @ResponseBody void getUserDepts(Long userId) {
		ValidateUtil.validRequired(userId, "用户ID");
		List<Dept> list = deptUserService.getUserDepts(userId);
		JSONArray ja = JsonUtil.toJSONArray(list);
		outJsonSuccess(ja.toString());
	}

	@RequestMapping("/deptUser_del.do")
	public @ResponseBody void delUserDepts(Long userId, Long deptId) {
		ValidateUtil.validRequired(userId, "用户ID");
		ValidateUtil.validRequired(deptId, "部门ID");
		deptUserService.deleteUser(userId, deptId);
		clearCache(userId);
		outJsonSuccess();
	}

	@RequestMapping("/delUsers.do")
	public @ResponseBody void delUsers(String userIds, Long deptId) {
		ValidateUtil.validRequired(deptId, "部门ID");
		deptUserService.deleteUsers(userIds, deptId);
		String[] ids = userIds.split(",");
		for (String userId : ids)
			clearCache(Long.valueOf(userId));
		outJsonSuccess();
	}

	@RequestMapping("/deptUser_resetPwd.do")
	public @ResponseBody void resetPwd(Long userId, Long deptId) {
		ValidateUtil.validRequired(userId, "用户ID");
		ValidateUtil.validRequired(deptId, "部门ID");
		User user = deptUserService.getUserById(userId);
		// String md5Pwd=new MD5().getMD5ofStr(IConstants.USER_DEFAULT_PWD);
		// user.setPassword(md5Pwd);
		deptUserService.doChangePwd(user);
		outJsonSuccess();
	}

	@RequestMapping("/toDistributeDeptUser.do")
	public String toDistributeDeptUser(Long deptId) {
		List users = deptUserService.getCurDeptUsers(getLoginUser().getDept().getId(), deptId);
		putInRequest("users", users, "deptId", deptId);
		return "system/deptUser_DistributionUser";
	}

	@RequestMapping("/toSaveDistribution.do")
	public @ResponseBody void toSaveDistribution(Long deptId, Long[] userIds) throws Exception {
		deptUserService.doSaveDistribution(deptId, userIds);
		for (Long userId : userIds)
			clearCache(userId);
		outJsonSuccess();

	}

	@RequestMapping("/toTransferPersion.do")
	public String toTransferPersion(Long deptId, Long userId) {
		putInRequest("deptId", deptId, "userId", userId);
		return "system/transferPerson";
	}

	@RequestMapping("/saveTranslation.do")
	public @ResponseBody void saveTranslation(Long inDeptId, Long outDeptId, Long userId) {


		deptUserService.doSaveTranslation(inDeptId, outDeptId, userId);
		clearCache(userId);
		outJsonSuccess();
	}

	@RequestMapping("/getTransferDeptTree.do")
	public @ResponseBody void getTransferDeptTree(Long userId) {
		SessionUser user = getLoginUser();
		
		final Long currDeptId = SessionUtil.getLoginDeptId();// user.isAdmin()?1:user.getDept().getId();
									// //当前操作人所在部门，即根节点
		final Long currParentId = 0L;// user.getDept().getParentId();
										// //当前操作人所在部门的上级部门
		final boolean flag = deptUserService.isRootUser(userId, currDeptId);// 判断要调出的人员是否在根部门中已有
		List<Dept> depts = deptUserService.getTransferDepts(currDeptId, userId);
		
		TreeHelper tree = new TreeHelper(
				new String[] { "id", "deptName", "deptNo", "parentId", "admin", "telPhone", "fax", "type", "sortNum" },
				depts, 3) {
			@Override
			public Object root() {
				return flag == true ? currDeptId : currParentId; // 如果被调出人员已经存在根部门，则ztree没有根节点
			}

			@Override
			public Object[] idTextData(Object[] nodeData) {
				return new Object[] { nodeData[0], nodeData[1] };
			}
		};
		outJson(tree);
	}


	/**
	 * 进入上传页面
	 * 
	 * @return
	 */
	@RequestMapping("/toUpload.do")
	public String toUpload() {
		return "file/file_upload";
	}

	/**
	 * 清除缓存
	 */
	private void clearCache(Long userId) {
		RedisClientUtil.delkeyObject(ICacheConstants.CACHE_AUTH_USER_DEPT + userId);
	}

}
